// 数据库基本配置
const MongoClient = require('mongodb').MongoClient;
const ObjectId = require('mongodb').ObjectId
const url = "mongodb://localhost:27017/";
const dbName = 'mongoTest'

class Mongo {
    dbo = null
    constructor() {
        // console.log('mongo init...');
        MongoClient.connect(url, (error, db) => {       //异步操作，connect连接数据库的工具
            if (error) throw error
            const dbo = db.db(dbName);
            this.dbo = dbo
        })
    }
    // 从后台获得数据
    find(collectionName, params = {}) {
        params.limit = params.limit || 10
        params.page = params.page-1 || 0
        params.sort = params.sort || { _id: -1 }
        return new Promise((resolve, reject) => {
            this.dbo.collection(collectionName).find(params.where).sort(params.sort)
                .skip(params.page * params.limit).limit(params.limit).toArray(function (err, result) {
                    if (err) throw err
                    resolve(result)
                })
        })
    }
    // 查询单条数据
    findOne(collectionName, params = {}) {
        return new Promise((resolve, reject) => {
            this.dbo.collection(collectionName).findOne(params, (error, result) => {
                if (error) throw error
                console.log("ddd",result);
                resolve(result)
            })
        })
    }
    // 获得数据条数
    count(collectionName, params = {}) {
        return new Promise((resolve, reject) => {
            this.dbo.collection(collectionName).find().count((err, total) => {
                if (err) throw err
                resolve(total)
            })
        })
    }
    // 新增数据
    insertOne(collectionName, params = {}) {
        return new Promise((resolve, reject) => {
            console.log(params);
            this.dbo.collection(collectionName).insertOne(params, (err, result) => {
                if (err) throw err
                resolve(result)
            })
        })
    }
    // 修改数据
    updateOne(collectionName, params = {}) {
        return new Promise((resolve, reject) => {
            this.dbo.collection(collectionName).updateOne(params.where, { $set: params.update }, (err, result) => {
                if (err) throw err;
                resolve(result)
            })
        })
    }
    // 删除单条数据
    deleteOne(collectionName, params = {}) {
        return new Promise((resolve, reject) => {
            this.dbo.collection(collectionName).deleteOne(params, (error, result) => {
                if (error) throw error;
                resolve(result)
            })
        })
    }
    // 删除多条数据
    deleteMany(collectionName, ids = []) {
        return new Promise((resolve, reject) => {
            ids = ids.map(item => ObjectId(item))
            this.dbo.collection(collectionName).deleteMany({ _id: { $in: ids } }, (error, result) => {
                if (error) throw error;
                resolve(result)
            });
        })
    }

}


module.exports = new Mongo()